﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using DslModeling=global::Microsoft.VisualStudio.Modeling;
using DslDiagrams=global::Microsoft.VisualStudio.Modeling.Diagrams;
using DslValidation=global::Microsoft.VisualStudio.Modeling.Validation;

namespace Salamanca.Saml
{

    [DslValidation.ValidationState(DslValidation.ValidationState.Enabled)]
    partial class FlowElement
    {

        /// <summary>Ensures that transition names flowing out of this element are unique.</summary>
        [DslValidation.ValidationMethod(DslValidation.ValidationCategories.Menu | DslValidation.ValidationCategories.Open | DslValidation.ValidationCategories.Save)]
        private void ValidateTransitionNames(DslValidation.ValidationContext context)
        {
            List<Transition> transitions=new List<Transition>();

            // All start points count as one
            StartPoint start=this as StartPoint;
            if (start!=null)
            {
                foreach (StartPoint sp in ActivityModel.Partition.ElementDirectory.FindElements<StartPoint>(true))
                    transitions.AddRange(sp.TransitionTo.Select<FlowElement, Transition>(fe => Transition.GetLink(sp, fe)));
            } else
                transitions.AddRange(TransitionTo.Select<FlowElement, Transition>(fe => Transition.GetLink(this, fe)));

            IEnumerable<IGrouping<string, Transition>> duplicates=transitions
                .GroupBy<Transition, string>(t => t.Name)
                .Where<IGrouping<string, Transition>>(g => g.Count<Transition>()>1);

            foreach (IGrouping<string, Transition> group in duplicates)
                context.LogError(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.SR.DuplicateTransitionName,
                        group.Key
                    ),
                    "SAML02",
                    group.Cast<DslModeling.ModelElement>().ToArray<DslModeling.ModelElement>()
                );
        }
    }
}
